/* Import modules */
var eventproxy = require('eventproxy');
var superagent = require('superagent');
var cheerio = require('cheerio');
var url = require('url');
var targetUrl = 'https://cnodejs.org/';

superagent.get(targetUrl).end(function(err, res) {
	/* Error handle */
	if (err) {
		return console.error(err);
	}
	var $ = cheerio.load(res.text);
	var ep = new eventproxy();
	var topicUrls = [];
	$('#topic_list .topic_title').each(function(idx, element) {
		var $element = $(element);
		var href = url.resolve(targetUrl, $element.attr('href'));
		topicUrls.push(href);
	});
	console.log(topicUrls);
	/* after() */
	ep.after('topic_html', topicUrls.length, function(topics) {
		topics = topics.map(function(topicPair) {
			var topicUrl = topicPair[0];
			var topicHtml = topicPair[1];
			var $ = cheerio.load(topicHtml);
			return ({
				title: $('.topic_full_title').text().trim(),
				href: topicUrl,
				comment1: $('.reply_content').eq(0).text().trim(),
			});
		});
		console.log('Final:');
		console.log(topics);
	});
	/* Fetch and emit() */
	topicUrls.forEach(function(topicUrl) {
		superagent.get(topicUrl).end(function(err, res) {
			console.log('Fetch ' + topicUrl + 'successful');
			ep.emit('topic_html', [topicUrl, res.text]);
		});
	});
});
